#include "globalAPI.h"
#include "wifi.h"
#include "zlog.h"

static char *cfgfile = "/etc/wpa_supplicant.conf";

int redbee_wifi_get_psk(char *ssid, char **psk)
{
    FILE *f        = NULL;
    char line[256] = {0};
    char *lineInfo = NULL;
    char *k = NULL, *v = NULL;
    char buf[35] = {0};

    sprintf(buf, "%s%s%s", "\"", ssid, "\"");

    f = fopen(cfgfile, "r");
    if (!f)
        return 0;

    while (!feof(f)) {
        if (!fgets(line, sizeof(line), f))
            break;

        lineInfo = redbee_strtok(line, "\n");
        k        = strtok(lineInfo, "=");
        v        = strtok(0, "=");
        dzlog_debug("1 %s:%s\n", k, v);
        if (k && v) {
            if (strcmp(v, buf) == 0) {
                if (!fgets(line, sizeof(line), f))
                    break;
                lineInfo = redbee_strtok(line, "\n");
                k        = strtok(lineInfo, "=");
                v        = strtok(0, "=");
                dzlog_debug("2 %s:%s\n", k, v);
                if (strstr(k, "psk") != NULL) {
                    *psk = strtok(v, "\"");
                    dzlog_debug("psk:%s\n", *psk);
                    fclose(f);
                    return 0;
                }
                *psk = NULL;
                fclose(f);
                return 0;
            }
        }
    }
    fclose(f);
    return -1;
}

int EnableAllList()
{
    char *file_from = "/etc/wpa_supplicant.conf";
    char *file_to   = "wpa_supplicant.conf";
    char *be_del    = "disable=1";
    FILE *fpf = NULL, *fpt = NULL;
    char line_str[100];
    int ret = 0;

    fpf = fopen(file_from, "r");
    fpt = fopen(file_to, "w");
    if (fpf == NULL || fpt == NULL) {
        dzlog_debug("open file error!");
        ret = 1;
        goto ERROR_EXIT;
    }

    while (fscanf(fpf, "%s", line_str) > 0) {
        if (strstr(be_del, line_str) == NULL) {
            dzlog_debug("%s\n", line_str);
            fprintf(fpt, "%s\n", line_str);
        }
    }

    if (shellCommand("~/test.sh", NULL, 0, false, true) < 0) {
        ret = -1;
        goto ERROR_EXIT;
    }

    dzlog_debug("operation done!\n");

    if (!remove(file_to)) {
        dzlog_debug("Removed %s\n", file_to);
    } else {
        perror("Remove");
    }

ERROR_EXIT:
    if (fpf != NULL)
        fclose(fpf);
    if (fpt != NULL)
        fclose(fpt);
    return ret;
}
